﻿using AutoMapper;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using TrackSystem.Contracts;
using TrackSystem.Entities.DataShaping;
using TrackSystem.Entities.Dtos.User;
using TrackSystem.Entities.Models;

namespace TrackSystem.API.Controllers
{
    /// <summary>
    /// 账号管理控制器
    /// </summary>
    [Route("api/account")]
    [ApiController]
    public class AccountController(UserManager<User> userManager, IMapper mapper) : ControllerBase
    {

        /// <summary>
        /// 注册新用户
        /// </summary>
        /// <param name="userForCreateDto">输入参数</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult<UserDto>> Register(UserForCreateDto userForCreateDto)
        {
            if (!ModelState.IsValid)
            {
                return ApiResult<UserDto>.Fail("输入数据个数不正确");
            }

            var user = mapper.Map<User>(userForCreateDto);
            var result = await userManager.CreateAsync(user, userForCreateDto.Password);
            if (!result.Succeeded)
            {
                string msg = "注册失败, ";
                foreach (var error in result.Errors)
                {
                    msg += $"{error.Description},";
                }
                return ApiResult<UserDto>.Fail(msg);
            }

            await userManager.AddToRoleAsync(user, "User");
            return ApiResult<UserDto>.Ok(mapper.Map<UserDto>(user), "注册成功");
        }
    }
}
